﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using MergeTool.ClassLib;
using MergeTool.ClassLib.Common;
using MergeTool.ClassLib.Configuration;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace MergeTool.UI.Helpers
{
    public class WorkItemValidator
    {

        public bool ValidateWit(List<ValidationResult> results, int workItemId)
        {
            WorkItemStore witStore;
            try
            {
                TfsConnection tfsConnection = TfsConnection.GetInstance();
                witStore = tfsConnection.GeTfsTeamProjectCollection().GetService<WorkItemStore>();
            }
            catch (Exception)
            {
                results.Add(new ValidationResult("Work item id could not be verified!"));
                return false;
            }

            try
            {
                witStore.GetWorkItem(workItemId);
            }
            catch (Exception)
            {
                results.Add(new ValidationResult("Invalid work item id!"));
                return false;
            }
            return true;
        }

        public bool ValidateChangeset(List<ValidationResult> results, int changesetId)
        {
            WorkItemStore witStore;
            if (changesetId > 0)
            {
                try
                {
                    MergeManager mergeManager = new MergeManager();
                    Changeset tempChangeset = mergeManager.GetChangesetDetails(changesetId);
                    if (
                        !tempChangeset.Changes[0].Item.ServerItem.StartsWith("$/" +
                                                                            Settings.GetInstance()
                                                                                .ConnectionInfo.TeamProject))
                    {
                        throw new Exception();
                    }
                }
                catch (Exception)
                {
                    results.Add(new ValidationResult("Invalid changeset id!"));
                    return false;
                }
            }
            
            return true;
        }
    }
}
